﻿namespace Leetcode.N1117;

using System.Threading;
public class H2O
{

    private readonly SemaphoreSlim hSemmaphore = new SemaphoreSlim(2, 2);
    private readonly SemaphoreSlim oSemmaphore = new SemaphoreSlim(1, 1);
    private int hCount = 0;
    private int oCount = 0;
    public H2O()
    {

    }

    public void Hydrogen(Action releaseHydrogen)
    {
        this.hSemmaphore.Wait();
        // releaseHydrogen() outputs "H". Do not change or remove this line.
        releaseHydrogen();
        Interlocked.Increment(ref this.hCount);
        this.Release();
    }



    public void Oxygen(Action releaseOxygen)
    {
        this.oSemmaphore.Wait();
        // releaseOxygen() outputs "O". Do not change or remove this line.
        releaseOxygen();
        Interlocked.Increment(ref this.oCount);
        this.Release();
    }

    private void Release()
    {
        if (this.hCount == 2 && this.oCount == 1)
        {
            lock (this)
            {
                if (this.hCount == 2 && this.oCount == 1)
                {
                    this.hCount = 0;
                    this.oCount = 0;
                    this.hSemmaphore.Release(2);
                    this.oSemmaphore.Release(1);

                }
            }
        }
    }
}